import { Component, Input, OnInit } from '@angular/core';
import { CaseService } from 'src/app/share/service/case.service';
import { ActionTypeService } from 'src/app/share/service/actionTypes.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ActivatedRoute } from '@angular/router';
import { ScenarioService } from 'src/app/share/service/scenario.service';
import { RESPONSE_DATA } from 'src/app/share/const/interfaces';
import { ACTION_TYPES, RESPONSE_CODE } from 'src/app/share/const/base.const';
import { TCase, TType, TScenario, TSortData } from '../types';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';

@Component({
  selector: 'app-cases',
  templateUrl: './cases.component.html',
  styleUrls: ['./cases.component.less'],
})
export class ShowCasesComponent implements OnInit {
  // drawer是否可见
  visible = false;

  title = 'case数据';
  //测试feature, 相当于page
  feature = '';
  //测试场景
  scenario = '';
  // feature下的 scenario对应的id
  @Input() scenarioId: number = -1;

  //表格loading状态
  tableLoading = false;
  // 表格数据
  tableData: TCase[] = [];
  // 操作类型
  actionTypes: TType[] = [];
  //编辑缓存数据
  editCache: { [key: number]: { edit: boolean; data: TCase } } = {};

  constructor(
    private caseService: CaseService,
    private actionTypeService: ActionTypeService,
    private message: NzMessageService,
    private scenarioService: ScenarioService
  ) {}

  ngOnInit(): void {}

  initData() {
    // 根据id查询Feature数据
    this.getScenarioById();
    // 根据sid查询所有的测试步骤
    this.queryTestCases();
    // 查询所有的操作类型
    this.queryActionTypes();
  }

  getScenarioById() {
    this.scenarioService.getScenarioById(this.scenarioId).subscribe((res) => {
      const { data } = res as RESPONSE_DATA<TScenario>;
      if (data) {
        const { scenario } = data;
        this.scenario = scenario;
      }
    });
  }
  // 拖拽排序, 放下时触发的动作
  drop(event: CdkDragDrop<string[]>): void {
    const _tableData = [...this.tableData];
    moveItemInArray(_tableData, event.previousIndex, event.currentIndex);
    this.tableData = [..._tableData];
    // 调用后端接口更新排序
    this.updateSort();
  }

  updateSort() {
    const sortedData: TSortData[] = [];
    this.tableData.map((item, idx) => {
      sortedData.push({
        id: item.id,
        sort: idx + 1,
      });
    });
    this.caseService.updateCaseSort(sortedData).subscribe((res) => {
      console.log('res---', res);
    });
  }

  // 查询所有的测试步骤
  queryTestCases() {
    // tableLoading  表格loading框
    this.tableLoading = true;
    this.caseService.getCases(this.scenarioId).subscribe((res) => {
      const { code, data } = res as RESPONSE_DATA<any>;
      if (code === RESPONSE_CODE.SUCCESS) {
        this.tableData = data;
        this.tableLoading = false;
        this.updateEditCache();
      }
    });
  }

  // 查询所有的操作类型
  queryActionTypes() {
    this.actionTypeService.getActionTypes().subscribe((response) => {
      const { data } = response as RESPONSE_DATA<TType[]>;
      this.actionTypes = data;
      // console.log("data--", data);
    });
  }

  getActionNameByType(type: string) {
    const act = this.actionTypes.find((t) => {
      return t.type === type;
    });
    return act?.name;
  }

  // 开始编辑
  startEdit(id: number): void {
    this.editCache[id].edit = true;
  }
  // 取消编辑
  cancelEdit(id: number): void {
    const index = this.tableData.findIndex((item) => item.id === id);
    const data = this.tableData[index];
    this.editCache[id] = {
      data: { ...data },
      edit: false,
    };
  }

  // 保存编辑
  saveEdit(data: TCase): void {
    // const { feature, scenario, sort } = this.editCache[data.id].data;
    const cacheData = this.editCache[data.id].data;
    const { elementId, type, value, sort, description, sid } = cacheData;

    // 当验证通过后往下走
    if (this.checkRowData(cacheData)) {
      const id = data.id;
      // 关闭当前行的编辑状态
      this.editCache[id].edit = false;

      if (data.isNew) {
        // 如果是新数据, 走新增接口
        this.caseService
          .postCase({
            elementId,
            type,
            value,
            sort: sort * 1,
            description,
            sid,
          })
          .subscribe((response) => {
            const { code } = response as RESPONSE_DATA<any>;
            if (code === RESPONSE_CODE.SUCCESS) {
              //重新查询数据
              this.queryTestCases();
            } else {
              this.message.error('请求接口出现错误');
              // console.log("response---", response);
            }
          });
      } else {
        // 不是新数据, 走更新接口
        this.caseService
          .updateCase(data.id, {
            elementId,
            type,
            value,
            sort: sort * 1,
            description,
          })
          .subscribe((response) => {
            const { code } = response as RESPONSE_DATA<any>;
            if (code === RESPONSE_CODE.SUCCESS) {
              //重新查询数据
              this.queryTestCases();
            } else {
              this.message.error('请求接口出现错误');
              // console.log("response---", response);
            }
          });
      }
    }
  }
  //检查输入的值
  checkRowData(data: TCase) {
    const { elementId, type, value, sort, description, sid } = data;

    if (type === ACTION_TYPES['输入']) {
      // 当type value是必填项
      if (!value) {
        this.message.warning('请填写输入的值');
        return false;
      }
    }

    // 当type 点击或者清除 id是必填项
    if (type === ACTION_TYPES['点击'] || type === ACTION_TYPES['清除']) {
      if (!elementId) {
        this.message.warning('请填写元素id');
        return false;
      }
    }

    // 当type是等待 或者检查元素时, value是必填项
    if (
      type === ACTION_TYPES['等待'] ||
      type === ACTION_TYPES['检查页面元素']
    ) {
      if (!value) {
        this.message.warning('请填写元素id');
        return false;
      }
    }
    return true;
  }

  //Table中新增行, 并处于可编辑状态
  addStep() {
    const rowData = {
      id: 0,
      sid: this.scenarioId * 1,
      sort: 0,
      elementId: '',
      type: '',
      description: '',
      value: '',
      isNew: true,
    };
    let maxSort = 0;
    let maxId = 0;

    this.tableData.map((d) => {
      if (d.id > maxId) {
        maxId = d.id;
      }
      if (d.sort > maxSort) {
        maxSort = d.sort;
      }
    });

    rowData.sort = maxSort + 1;
    rowData.id = maxId + 1;
    this.tableData = [...this.tableData, rowData];
    // id 用作编辑操作key
    this.editCache[rowData.id] = {
      edit: true,
      data: { ...rowData },
    };
  }

  // 删除测试步骤
  deleteStep(data: TCase, i: number) {
    if (data.isNew) {
      const _tableData = this.tableData;
      // 按照下标删除元素
      _tableData.splice(i, 1);
      this.tableData = [..._tableData];
    } else {
      //调用接口删除元素
      this.caseService.deleteCase(data.id).subscribe((response) => {
        const { code } = response as RESPONSE_DATA<any>;
        if (code === RESPONSE_CODE.SUCCESS) {
          //重新查询数据
          this.queryTestCases();
        } else {
          this.message.error('请求删除接口出错');
        }
      });
    }
  }

  copyStep(data: TCase) {
    this.caseService.copyCase(data.id).subscribe((res) => {
      const { code } = res as RESPONSE_DATA;
      if (code == RESPONSE_CODE.SUCCESS) {
        this.message.success('复制成功');
        this.queryTestCases();
      }
    });
  }

  //更新编辑缓存
  updateEditCache(): void {
    this.tableData.forEach((item) => {
      this.editCache[item.id] = {
        edit: false,
        data: { ...item },
      };
    });
  }

  showDetailsDrawer() {
    this.initData();
    this.visible = true;
    // console.log('查看详细信息----', this.sid);
  }
  close() {
    this.visible = false;
  }
}
